import { login, getPerson } from '@/api/login'
import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router'
import { Message } from 'element-ui'

Vue.use(Vuex)
import createPersistedState from "vuex-persistedstate"
export default new Vuex.Store({
  state: {
    isCollapse: false,
    name: '',
    token: ''
  },
  getters: {
  },
  mutations: {
    CHANGE_COLLAPSE(state) {
      state.isCollapse = !state.isCollapse
    },
    SET_NAME(state, name) {
      state.name = name
    },
    SET_TOKEN(state, token) {
      state.token = token
    },
    RESET(state) {
      state.token = ''
      state.name = ''
      localStorage.removeItem('name')
      localStorage.removeItem('token')
    }
  },
  actions: {
    Collapse({ commit }) {
      commit("CHANGE_COLLAPSE")
    },
    //登录
    goLogin({ commit }, data) {
      login(data).then(res => {
        if (res.code == 200) {
          localStorage.setItem('token', res.token)
          Message.success('登录成功')
          // this.getUserInfo()
          router.push({
            path: '/home'
          })
          // console.log(res, '32222')
          // commit('SET_NAME', res.data.name)
          commit('SET_TOKEN', res.token)
          //存本地一份
          // localStorage.setItem('name', res.data.name)
        }
      })
        .catch((err) => {
          Message.error(err.msg)
        })
    },
    // 获取个人信息
    getUserInfo({ commit }) {
      getPerson().then(res => {
        console.log(res, '======');
        commit('SET_NAME', res.user.nickName)
      })
        .catch(() => { })
    },

    //退出登录
    outLogin({ commit }) {
      commit('RESET')
      router.push({
        path: '/login'
      })
    }
  },

  modules: {
  },
  // 配置就持久化插件
  plugins: [

    createPersistedState({
      // 默认存到localstorage
      // 
      storage: localStorage,
      // 存储的key名
      key: 'my-key',
      // 存储指定变量
      paths: ['token']
    })
  ],
})
